package com.ych.DemoSSM.common.biz.service.impl;

import com.ych.DemoSSM.common.util.SystemUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Servlet Filter implementation class UrlRewriteFilter
 */
@Component("UrlRewriteFilter")
public class UrlRewriteFilter implements Filter {

    @Value("${redirectDomain}")
    private String redirectDomain;

    @Value("${serverDomain}")
    private String serverDomain;

    /**
     * Default constructor.
     */
    public UrlRewriteFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String userID = "";
        HttpSession session = httpServletRequest.getSession();
        if (session != null) {
            Map<String, Object> userInfo = (Map<String, Object>) session.getAttribute("userInfo");
            if (userInfo != null) {
                userID = (String) userInfo.get("userID");
            }
        }

        Cookie[] cookies = httpServletRequest.getCookies();
        String ck_user_uuid = "";
        String ck_user_id = "";
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();

                if ("ck_user_id".equals(name)) {
                    ck_user_id = value;
                }
                if ("ck_user_uuid".equals(name)) {
                    ck_user_uuid = value;
                }
            }
        }

        if (StringUtils.isBlank(ck_user_uuid) || (StringUtils.isNotBlank(userID) && StringUtils.isNotBlank(ck_user_id)
                && !StringUtils.equalsIgnoreCase(userID, ck_user_id))) {
            ck_user_uuid = SystemUtils.getUUID();
            Cookie cookie = new Cookie("ck_user_uuid", ck_user_uuid);
            httpServletResponse.addCookie(cookie);
        }
        if (StringUtils.isNotBlank(userID)) {
            Cookie cookie = new Cookie("ck_user_id", URLEncoder.encode(userID, "utf-8"));
            httpServletResponse.addCookie(cookie);
        }


        // 获取域名
        String serverName = request.getServerName();
        if (StringUtils.isNotBlank(serverName) && StringUtils.isNotBlank(redirectDomain)) {
            int end = serverName.indexOf(redirectDomain);
            if (end == 0) { // 判断是否是example.com
                // 获取请求路径
                String path = httpServletRequest.getRequestURI();
                String queryString = (httpServletRequest.getQueryString() == null ? ""
                        : "?" + httpServletRequest.getQueryString()); // 获取路径中的参数

                httpServletResponse.setStatus(301);
                httpServletResponse.setHeader("Location", "http://" + serverDomain + path + queryString);
                httpServletResponse.setHeader("Connection", "close");
                return;
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    @Override
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}
